// WeChat Mini Program HTTP utility
const baseURL = 'https://oaa00e.top/bjnsWalk';
const { STORAGE_KEY_TOKEN } = require('../constant/storage_keys.js');

function getToken() {
  let token = '';
  try {
    token = wx.getStorageSync(STORAGE_KEY_TOKEN) || '';
  } catch (e) { }
  return token;
}

function setToken(token) {
  try {
    wx.setStorageSync(STORAGE_KEY_TOKEN, token);
  } catch (e) { }
}

function removeToken() {
  try {
    wx.removeStorageSync(STORAGE_KEY_TOKEN);
  } catch (e) { }
}

function request(options) {
  return new Promise((resolve, reject) => {
    const token = getToken();
    const header = {
      'Content-Type': 'application/json'
    };

    if (token) {
      header['Authorization'] = 'Bearer ' + token;
    }

    wx.request({
      url: baseURL + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: header,
      success: (res) => {
        // 检查是否有新token
        const newToken = res.header['x-refresh-token'] || res.header['X-Refresh-Token'];
        if (newToken) {
          setToken(newToken);
        }

        if (res.statusCode === 401) {
          removeToken();
          wx.showToast({ title: '登录已过期，请重新登录', icon: 'none' });
          wx.redirectTo({ url: '/pages/login/login' });
          reject(new Error('Unauthorized'));
          return;
        }

        resolve(res);
      },
      fail: (err) => {
        wx.showToast({ title: '网络错误', icon: 'none' });
        reject(err);
      }
    });
  });
}

const http = {
  get: (url, data) => request({ url, method: 'GET', data }),
  post: (url, data) => request({ url, method: 'POST', data }),
  put: (url, data) => request({ url, method: 'PUT', data }),
  delete: (url, data) => request({ url, method: 'DELETE', data })
};

const defaultTeamAvatarUrl = baseURL + '/team/defaultAvatar';

module.exports = Object.assign(http, { getToken, setToken, removeToken, baseURL, defaultTeamAvatarUrl }); 